package com.mvc.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.mvc.entity.Student;
import com.mvc.entity.Users;
import com.mvc.service.StudentService;

@Controller
public class AjaxController {
	private StudentService studentService;
	
	@RequestMapping("/getlist.do")
	public void getList(HttpServletResponse response)
	{
		List<Student> list = studentService.getStudentList();
		List<Users> users=new ArrayList<Users>();
		for (Student student : list) {
			Users user=new Users();
			user.setId(student.getId().toString());
			user.setName(student.getUser());
			user.setEmail(student.getPsw());
			users.add(user);
		}
		Gson gson=new Gson();
		Map<String, Object> map=new HashMap<String,Object>();
		map.put("success", true);
		map.put("users",users);
		try {
			response.getWriter().print(gson.toJson(map));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	@RequestMapping("/update.do")
	@ResponseBody
	public Map<String, Object>  update(@RequestBody Users user,HttpServletResponse response)
	{
			Map<String,Object> map=new HashMap<String,Object>();
			
			Student student=new Student();
			student.setId(Integer.parseInt(user.getId()));
			student.setUser(user.getName());
			student.setPsw(user.getEmail());
			
			
			
			studentService.save(student);
			map.put("success", true);
			return map;
		
	}
	
	

	public StudentService getStudentService() {
		return studentService;
	}
	@Autowired
	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}
}
